import React, {Component} from "react";
import {
    ActivityIndicator,
    Dimensions,
    FlatList, Image,
    Platform,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import Header from "../../components/header";
import Constant from "../../utils/Constant";
import SeekItemView from "../seekCenter/seekComponents/SeekItemView";
import NoData from "../../utils/NoData";
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import {CarSaleStatus, PermissionType} from "../../utils/Enum";
import AsyncImage from "../../components/image/AsyncImage";
import {
    getCarRegisterDate,
    getImgUrl,
    getMileFormat,
    getPerm,
    getPriceFormat,
    priceFenToYuanFormat
} from "../../utils/ComFunction";
import {ToastToUser} from "../../utils/CustomToast";
import LinearGradient from "react-native-linear-gradient";


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

let navigation;

export default class MyOfferPriceListPage extends Component {
    constructor( props){
        super(props);

        let priceOperatePerm = getPerm(PermissionType.Permission_EnableOfferPriceOperate)

        this.state = {
            priceOperatePerm,
            isFranchisee: Constant.userInfo.isFranchisee ? Constant.userInfo.isFranchisee : 0,//是否加盟商 0否1是

            offerPriceList: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,
            pageSize: 4,
        }
    }

    componentDidMount(){
        this.getOfferPriceList()
    }

    componentWillUnmount(){

    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'我的报价'} />

                {this.offerPriceListData()}

            </View>
        )
    }

    offerPriceListData(){
        return (
            <View
                style={{
                    flex: 1,
                    marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0,
                }}>
                <FlatList
                    data={this.state.offerPriceList}
                    renderItem={this.renderItemView.bind(this)}
                    keyExtractor={item => item?.id || Math.random().toString()} // 使用唯一键
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.1}
                />
            </View>
        );
    }

    renderItemView({item, index}) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.cardContainer}
                activeOpacity={0.8}
                onPress={() => {
                    navigation.navigate('CarOfferPriceDetailPage', {
                        carId: item.carId,
                        saleStatus: item.saleStatus,
                        merchantId: item.merchantId
                    })
                    // navigation.navigate('CarOfferPricePage',{carId:item.carId,merchantId:item.merchantId})
                }}
            >
                <View style={styles.itemCompanyContain}>
                    <Text numberOfLines={1} style={styles.companyText}>{item.merchantAbbreviation}</Text>
                    {/*<Text style={styles.companyText}>{this.getQuotationProgressStatus(item)}</Text>*/}
                </View>

                <View style={{ backgroundColor: '#f6f6f6', height: 1 }}></View>

                <View style={styles.carContainer}>

                    <View style={styles.labelBox}>
                        {
                            item.detectionStatus == 3 ?
                                <Image style={{ width: 59, height: 18, marginRight: 4 }} source={require('source/image/detection_auth.png')} />
                                :
                                null
                        }

                        {
                            item.isReported == 1 ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#FFF5E6' }]}>
                                    <Text style={[styles.labelText, { color: '#F99802' }]}>有维保</Text>
                                </View>
                                :
                                null
                        }

                        {
                            item.saleStatus == CarSaleStatus.CarSaleStatusReserved ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#F1FAED' }]}>
                                    <Text style={[styles.labelText, { color: '#6ECC49' }]}>已预订</Text>
                                </View>
                                :
                                null
                        }

                    </View>

                    <AsyncImage
                        source={{ uri: getImgUrl(item.mainPic) }}
                        defaultSource={require('source/image/icon_car_default.png')}
                        style={styles.carImage}
                        resizeMode="cover"
                    />

                    <View style={styles.infoContainer}>
                        <View>
                            <Text style={styles.carName} numberOfLines={1} ellipsizeMode='tail'>{item.seriesName + ' ' + item.speciesName}</Text>

                            <Text style={styles.subInfo}>
                                {this.getSubCarInfo(item)}
                            </Text>
                        </View>


                        <View style={styles.priceContain}>
                            <Text style={styles.price}>
                                {this.getPriceFormat(item)}
                                {/*已报价: {priceFenToYuanFormat(item.buyerLastCarQuotationRecordRO.quotationPrice)}*/}
                            </Text>
                        </View>

                    </View>
                </View>

                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end'}}>
                    {/*<View style={{borderRadius:99, backgroundColor:'#FFDB1B', width: 75, height: 28, alignItems:'center', justifyContent:'center'}}>*/}
                    {/*   <Text style={{fontSize: 13, color:'#333333'}}>立即报价</Text>*/}
                    {/*</View>*/}

                    {this.getBottomBtn(item)}

                    <TouchableOpacity onPress={() => {
                        this.consultOnline(item)
                    }}>
                        <Image style={[styles.msgCountImg, {marginLeft: 8}]} source={require('source/image/offerPrice/liaotian.png')}></Image>
                    </TouchableOpacity>

                </View>
            </TouchableOpacity>
        );
    }

    getPriceFormat(item) {
        if(!item.buyerLastCarQuotationRecordRO){
            return null
        }
        let recordRO = item.buyerLastCarQuotationRecordRO
        if (recordRO.quotationRecordStatus == 0 || recordRO.quotationRecordStatus == 4 || recordRO.quotationRecordStatus == '') {// 未报价(显示立即报价)
            if(recordRO.historyRO && recordRO.historyRO.isReject == '1'){ // 修改报价
                return "已报价:" + priceFenToYuanFormat(item.buyerLastCarQuotationRecordRO.quotationPrice)
            }else{
                if(recordRO.quotationRecordStatus == 4){
                    return "已取消"
                }
                return "未报价"
            }
        } else if (recordRO.quotationRecordStatus == 1) {// 已报价(显示待确认)
            if (recordRO.historyRO.isReject == '1') {//报价被驳回(显示修改报价)
                return "已报价:" + priceFenToYuanFormat(item.buyerLastCarQuotationRecordRO.quotationPrice)
            } else {
                return "已报价:" + priceFenToYuanFormat(item.buyerLastCarQuotationRecordRO.quotationPrice)
            }

        } else if (recordRO.quotationRecordStatus == 2) {
            return "已确认:" + priceFenToYuanFormat(item.buyerLastCarQuotationRecordRO.quotationPrice)
        }
    }

    getBottomBtn(item) {
        // console.log('item.quotationRecordStatus=', item)
        if(!this.state.priceOperatePerm){
            return  null
        }
        if(!item.buyerLastCarQuotationRecordRO){
            return null
        }
        let recordRO = item.buyerLastCarQuotationRecordRO
        if (recordRO.quotationRecordStatus == 0 || recordRO.quotationRecordStatus == 4 || recordRO.quotationRecordStatus == '') {// 未报价(显示立即报价)

            if(recordRO.historyRO && recordRO.historyRO.isReject == '1'){
                return (
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={() => {
                            navigation.navigate('CarOfferPricePage', { carId: item.carId, merchantId: item.merchantId, isEdit: true })
                        }}
                    >
                        <View style={styles.offerPriceButton}>
                            <Text style={styles.offerPriceButtonText}>修改报价</Text>
                        </View>
                    </TouchableOpacity>
                )
            }else{
                return (
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={() => {
                            navigation.navigate('CarOfferPricePage', { carId: item.carId, merchantId: item.merchantId, isEdit: false })
                        }}
                    >
                        <View style={styles.offerPriceButton}>
                            <Text style={styles.offerPriceButtonText}>立即报价</Text>
                        </View>
                    </TouchableOpacity>
                )
            }

        } else if (recordRO.quotationRecordStatus == 1) {// 已报价(显示待确认)
            if (recordRO.historyRO.isReject == '1') {//报价被驳回(显示修改报价)
                return (
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={() => {
                            navigation.navigate('CarOfferPricePage', { carId: item.carId, merchantId: item.merchantId, isEdit: true })
                        }}
                    >
                        <View style={styles.offerPriceButton}>
                            <Text style={styles.offerPriceButtonText}>修改报价</Text>
                        </View>
                    </TouchableOpacity>
                )
            } else {
                return (
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={() => {

                            this.quotationReject(recordRO)
                        }}
                    >
                        <View style={styles.offerPriceButtonBorder}>
                            <Text style={styles.offerPriceButtonText}>取消报价</Text>
                        </View>

                    </TouchableOpacity>
                )
            }

        } else if (recordRO.quotationRecordStatus == 2) {
            return (
                <TouchableOpacity
                    activeOpacity={0.8}
                    onPress={() => {
                        navigation.navigate('BuyerStartOrderPage', { carId: item.carId, merchantId: recordRO.buyerMerchantId })
                    }}
                >
                    <View style={styles.offerPriceButton}>
                        <Text style={styles.offerPriceButtonText}>确认订单</Text>
                    </View>

                </TouchableOpacity>
            )
        }
    }

    // 取消订单
    quotationReject(item) {
        let params = {
            quotationRecordId: item.quotationRecordId,
            operator: Constant.userInfo.fullname
        }
        HttpUtils.postRequest(HttpUrls.quotationCancel, params).then(result => {

            if (result.code == 0) {
                ToastToUser('取消成功')
                this.refreshData()
            } else {
                ToastToUser(result.msg ? result.msg : result.statusText)
            }
        }).catch(err => {

        })
    }


    // 在线咨询
    consultOnline(item) {
        let param = {
            carId: item.carId,
            buyerMerchantId: Constant.userInfo.merchantId,
            sellerMerchantId: item.merchantId,
            buyerUserId: Constant.userInfo.userId,
        }

        if (this.Loading) {
            this.Loading.show();
        }

        HttpUtils.postRequest(HttpUrls.quotationConsult, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {

                    setTimeout(() => {
                        navigation.navigate('MessageChat', {
                            imGroupId: result.data.imGroupId,
                            carId: this.state.carId
                        })
                    }, 500);

                } else {
                    ToastToUser(result.msg + '')
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    //刷新数据
    refreshData = () => {
        console.log('刷新数据')
        this.setState(
            {
                isRefresh: true,
                pageNo: 1,
                offerPriceList: [],
                showFoot: 1,
            },
            function () {
                this.getOfferPriceList();
            },
        );
    }

    renderEmpty() {
        return <NoData Desc="暂无数据" style={{marginTop: gREM(100)}} />;
    }

    // 底部加载更多
    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot == 1) {
            return null;
        }
        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1,
            },
            function () {
                this.getOfferPriceList();
            },
        );
    }

    // 获取我的报价
    getOfferPriceList() {
        let params = {
            pageNo: this.state.pageNo,
            pageSize: this.state.pageSize,
            merchantId: Constant.userInfo.merchantId,
            joinQuotationCenter: 1,
            saleStatus: '2',
        }

        /**
         * system_car_quotation:平台查询传递
         buyer_car_quotation:买家查询传递
         seller_car_quotation:卖家查询传递
         */
        if (this.state.isFranchisee == 1) {//加盟商作为卖家
            params['searchChannel'] = 'seller_car_quotation'
        } else {//经销商作为买家
            params['searchChannel'] = 'buyer_car_quotation'
        }

        // {"pageNo":1,"pageSize":20,"merchantId":1006281,"joinQuotationCenter":1,"saleStatus":"2","searchChannel":"buyer_car_quotation","userId":106717162}

        params['quotationProgressStatusList'] = [2,4]
        params['isQueryMyQuotationRecord'] = 1

        //HttpUrls.searchCars  HttpUrls.getQuotationOrderList
        HttpUtils.postRequest(HttpUrls.searchCars, params)
            .then((result) => {

                let code = result.code
                if (code == 0) {

                    let resultList = result.data.resultList

                    console.log('resultList', resultList)
                    if (resultList.length > 0) {
                        this.setState({
                            showFoot: 2,
                            offerPriceList: this.state.offerPriceList.concat(resultList),
                        })
                    } else {
                        this.setState({
                            showFoot: 1,  // 加载完成
                        })
                    }

                    this.setState({
                        isRefresh: false,

                    })
                } else {
                    this.setState({
                        isRefresh: false,

                    })
                }
            })
            .catch((error) => {
                this.setState({
                    isRefresh: false,

                })
            });
    }

    getSubCarInfo(item) {

        let carInfoStr = ''
        if (item.registerDate && item.registerDate != null) {
            carInfoStr = getCarRegisterDate(item.registerDate)
        }

        if (item.mileage && item.mileage != 0) {
            carInfoStr = carInfoStr + ' | ' + getMileFormat(item.mileage)
        }

        if (item.cityName && item.cityName != '') {
            if (carInfoStr != '') {
                carInfoStr = carInfoStr + ' | ' + item.cityName
            } else {
                carInfoStr = item.cityName
            }

        }

        return carInfoStr
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },


    cardContainer: {
        backgroundColor: '#fff',
        paddingHorizontal: 15,
        paddingBottom: 15,
        marginTop: 10,
        flexDirection: 'column',
        width: '100%',
    },
    itemCompanyContain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        height: 44,
        alignItems: 'center'
    },
    companyText: {
        fontSize: 14,
        color: '#333333'
    },
    carContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
    },
    carImage: {
        width: 120,
        height: 85,
        borderRadius: 4,
        backgroundColor: '#f5f5f5',
    },
    infoContainer: {
        flex: 1,
        marginLeft: 8,
        height: 76,
        flexDirection: 'column',
        justifyContent: 'space-between',
    },
    carName: {
        fontSize: 14,
        fontWeight: '500',
        marginBottom: 5,
        color: '#333',
    },
    subInfo: {
        fontSize: 12,
        color: '#999999',
        marginTop: 3,
    },
    price: {
        fontSize: 14,
        color: '#ED542E',
        fontWeight: '500',
    },
    priceContain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },

    labelBox: {
        zIndex: 1000,
        position: 'absolute',
        left: 4,
        top: 4,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    labelItemBox: {
        marginRight: 4,
        paddingHorizontal: 6,
        height: 18,
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 2,
        backgroundColor: '#F4F4F4'
    },
    labelText: {
        fontSize: 10,
        color: '#FF7B00'
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

    // 报价按钮
    offerPriceButton: {
        borderRadius:99,
        backgroundColor:'#FFDB1B',
        width: 75,
        height: 28,
        alignItems:'center',
        justifyContent:'center'
    },

    offerPriceButtonBorder: {
        borderRadius:99,
        borderWidth:1,
        borderColor:'#E5E5E5',
        width: 75,
        height: 28,
        alignItems:'center',
        justifyContent:'center'
    },

    offerPriceButtonText: {
        fontSize: 13,
        color:'#333333'
    },

})